<template>
  <div class="main-page-content-router-tag">
    <a-tag
      v-for="item in userStore.tags"
      :key="item.name"
      :closable="item.closable"
      class="main-page-content-router-tag-item"
      @close="(e) => closeTag(item)"
      @click="(e) => router.push(item.path)"
      ><span v-if="item.path == $route.path" class="main-page-content-router-tag-item-active"></span
      >{{ item.name }}</a-tag
    >
  </div>
</template>

<script setup>
import { ref, watch, getCurrentInstance } from 'vue'
import router from '@/router'
import { useUserStore } from '@/stores'
const userStore = useUserStore()

const { proxy } = getCurrentInstance()
watch(
  () => proxy.$route,
  (newValue) => {
    let tag = userStore.tags.filter((item) => item.path === newValue.path)
    if (!tag.length) {
      let closable = newValue.name !== '首页'
      userStore.setTags({ name: newValue.name, path: newValue.path, closable })
    }
  },
  { immediate: true }
)

const closeTag = (tag) => {
  let index = userStore.tags.findIndex((item) => {
    return item.path === tag.path
  })
  if (index !== -1) {
    userStore.delTags(index)
    if (tag.path === proxy.$route.path) {
      router.push(userStore.tags[userStore.tags.length - 1].path)
    }
  }
}
</script>

<style scoped lang="scss">
.main-page-content-router-tag {
  height: 30px;
  display: flex;
  align-items: center;
  box-shadow: 1px 5px 2px rgba(0, 0, 0, 0.1);
  padding: 0 10px;
  .main-page-content-router-tag-item {
    cursor: pointer;
  }
  .main-page-content-router-tag-item-active {
    display: inline-block;
    width: 10px;
    height: 10px;
    margin-right: 5px;
    border-radius: 50%;
    border: 1px solid rgba(0, 0, 0, 0.5);
  }
}
</style>